package org.itboys.mobile.service.mysql.mobile.income;

import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mdl.conmon.ErroException;
import org.itboys.mdl.entity.mongo.account.SundayAccount;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.income.MdlIncomeCashedMapper;
import org.itboys.mobile.dao.income.MdlIncomeDetailMapper;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.income.MdlIncome;
import org.itboys.mobile.entity.mysql.income.MdlIncomeCashed;
import org.itboys.mobile.entity.mysql.income.MdlIncomeDetail;
import org.itboys.mobile.entity.mysql.order.MdlOrder;
import org.itboys.mobile.service.mongo.mobile.account.SundayAccountService;
import org.itboys.mobile.service.mongo.mobile.member.SundayMobileMemberService;
import org.itboys.mongodb.service.BaseMySqlService;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：zzq
 * 时间：2017/12/25
 * 描述：迈迪龙_手机端_收益
 */
@Service
public class MdlMobileIncomeService extends BaseMySqlService<MdlIncome>{
    @Autowired
    private MdlIncomeCashedMapper cashedMapper;
    @Autowired
    private MdlIncomeDetailMapper detailMapper;
    @Autowired
    private SundayAccountService accountService;
    @Autowired
    private SundayMobileMemberService memberService;

    /**
     * 获取用户收益主表
     * @param memberId
     * @return
     */
    @Transactional
    public MdlIncome getIncome(Long memberId){
        //Map<String,Object> result = new HashMap<String, Object>();
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("memberId", memberId);
        MdlIncome income=null;
        List<MdlIncome> incomes=super.select(param);
        if(ListUtil.isNotNull(incomes)){
            income=incomes.get(0);
        }else{
            income = new MdlIncome(memberId);
            super.insert(income);
            income =  super.find(income.getId());
        }
        return income;
    }

    /**
     * 获取收益记录
     * @param request
     * @param memberId
     * @param type  代理商查询收益时
     * @return
     */
    public List<Map<String,Object>>getIncomeRecord(HttpServletRequest request, Long memberId,Integer type){
        Map<String,Object> param = ParamUtil.packageMysqlPageParam(request);
        SundayMember member=memberService.getById(memberId);
        List<SundayMember> salesMans=null;
        if(member.getUserType()==SundayCommonConstants.USER_TYPE_AGENT){
            //查看代理商自己的收益记录
            if(type==1){
                param.put("memberId", memberId);
            //查看代理商下属销售员的收益记录
            }else if(type==2){
                param.clear();
                List<Long> salesManIds=new ArrayList<Long>();
                param.put("agentId", memberId);
                param.put("userType",SundayCommonConstants.USER_TYPE_SALESMAN);

                salesMans=memberService.list(param);
                if(ListUtil.isNull(salesMans)){
                    return null;
                }else {
                    for(SundayMember salesMan:salesMans){
                        salesManIds.add(salesMan.getId());
                    }
                    param.put("salesManIds",salesManIds);
                }

            }


        }else if(member.getUserType()==SundayCommonConstants.USER_TYPE_SALESMAN){
            param.put("memberId",memberId);
        }

        List<MdlIncomeDetail>details=detailMapper.select(param);
        List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
        for(MdlIncomeDetail detail:details){
            Map<String,Object> result = new HashMap<String, Object>();
            //匹配销售员的姓名，账号，头像
            if(ListUtil.isNotNull(salesMans)){
                for(SundayMember salesMan:salesMans){
                    if(detail.getMemberId().longValue()==salesMan.getId()){
                        result.put("nickName",salesMan.getNickName());
                        result.put("userName",salesMan.getUserName());
                        result.put("image",salesMan.getImage());
                    }
                }
            }
            result.put("amount", detail.getRevenueAmount().setScale(2, BigDecimal.ROUND_UP));
            result.put("orderId", detail.getOrderId());
            result.put("orderNo", detail.getOrderNo());
            result.put("remark", detail.getRemark());
            result.put("createTime", detail.getCreateTime());
            results.add(result);
        }
        return results;
    }

    /**
     * 获取提现记录
     * @param request
     * @param memberId
     * @return
     */
    public List<Map<String,Object>> getCashRecord(HttpServletRequest request,Long memberId){
        Map<String,Object> param = ParamUtil.packageMysqlPageParam(request, "");
        param.put("memberId", memberId);
        List<MdlIncomeCashed>casheds=cashedMapper.select(param);

        List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
        for(MdlIncomeCashed cashed:casheds){
            Map<String,Object> result = new HashMap<String, Object>();
            result.put("amount", cashed.getApplyAmount().setScale(2,BigDecimal.ROUND_UP));
            result.put("account", cashed.getAccount());
            result.put("bank", cashed.getBank());
            result.put("statusStr", cashed.getStatusStr());
            result.put("stataus", cashed.getStatus());
            result.put("createTime", cashed.getCreateTime());

            results.add(result);
        }

        return results;
    }

    /**
     * 申请提现
     * @param memberId
     * @param applyAmount
     * @param accountId
     */
    @Transactional
    public void applyCash(Long memberId,BigDecimal applyAmount,Long accountId){
        //找到用户的收益主表
        MdlIncome income = getIncome(memberId);
        if(applyAmount.compareTo(income.getAbleRevenue())==1){
            throw new ErroException("当前可提现金额为："+income.getAbleRevenue());
        }
        //updateIncome(memberId, applyAmount, null, Finals.INCOME_TYPE_CASHED);

        MdlIncomeCashed cash = new MdlIncomeCashed();
        cash.setApplyAmount(applyAmount);
        cash.setAbleAmount(income.getAbleRevenue());
        cash.setMemberId(memberId);
        cash.setStatus(SundayCommonConstants.INCOME_YSQ);
        SundayAccount account = accountService.getById(accountId);
        cash.setBank(account.getBankName());
        cash.setName(account.getName());
        cash.setAccount(account.getAccountNumber());
        cash.setRemark(SundayCommonConstants.INCOME_TYPE_CASHED_MSG);
        //保存提现记录
        cashedMapper.insert(cash);
        //收益主表里可用金额减去本次提现金额。
        income.setAbleRevenue(income.getAbleRevenue().subtract(applyAmount));
        //冻结本次申请金额收益。2016年11月28日
        income.setFrozenRevenue(income.getFrozenRevenue().add(applyAmount));
        super.update(income);
    }


    public void updateIncome(
            Long memberId,
            BigDecimal amount,
            MdlOrder order, Integer type){
        MdlIncome income =getIncome(memberId);
        String remark="";

        if(type==SundayCommonConstants.INCOME_TYPE_BUSINESS||
                type==SundayCommonConstants.INCOME_TYPE_ORDER_RETURN||
                type==SundayCommonConstants.INCOME_TYPE_ORDER_CANCEL||
                type==SundayCommonConstants.INCOME_TYPE_CASHED_DISAGGREE){

            if(type==SundayCommonConstants.INCOME_TYPE_BUSINESS){
                remark=SundayCommonConstants.INCOME_TYPE_BUSINESS_MSG;
            }else if(type==SundayCommonConstants.INCOME_TYPE_ORDER_RETURN){
                remark=SundayCommonConstants.INCOME_TYPE_ORDER_RETURN_MSG;
            }else if(type==SundayCommonConstants.INCOME_TYPE_ORDER_CANCEL){
                remark=SundayCommonConstants.INCOME_TYPE_ORDER_CANCEL_MSG;
            }
            MdlIncomeDetail detail=new MdlIncomeDetail();
            detail.setIncomeId(income.getId());
            detail.setMemberId(memberId);
            detail.setOrderId(order.getId());
            detail.setOrderNo(order.getOrderNo());
            detail.setOrderAmount(order.getPayAmount());
            detail.setRevenueAmount(amount);
            detail.setRemark(remark);
            income.setTotalRevenue(income.getTotalRevenue().add(amount));
            income.setAbleRevenue(income.getAbleRevenue().add(amount));
            super.update(income);
            detailMapper.insert(detail);
        }

        //扣减收益的
        //4，消费抵扣-，8，提现扣减-(不在此处理)
/*        if(type==SundayCommonConstants.INCOME_TYPE_BUY){

            HaoYiIncomeCashed cash = new HaoYiIncomeCashed();
            cash.setApplyAmount(amount);
            cash.setAbleAmount(income.getAbleRevenue());
            cash.setMemberId(memberId);
            cash.setStatus(Finals.INCOME_YSQ);
            //HaoYiAccount account = accountService.getById(accountId);
            //cash.setBank(account.getBankName());;
            //cash.setName(account.getBankRealName());
            //cash.setAccount(account.getBankAccountNo());
            cash.setRemark(remark);
            //收益主表里可用金额减去本次提现金额。

            income.setAbleRevenue(income.getAbleRevenue().subtract(amount));
            //保存提现记录
            cashedMapper.insert(cash);
            //更新收益
            super.update(income);
        }*/
    }


}
